package com.yupi.springbootinit.mq;

import com.rabbitmq.client.*;

import java.util.HashMap;
import java.util.Map;

public class DlxConsumer {

    private static final String DEAD_EXCHANGE_NAME = "dlx";
    private static final String EXCHANGE_NAME = "direct2-exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        //配置死信交换机和死信队列
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", "outsourcing");

        //创建队列
        String queueName1 = "xiaocat";
        channel.queueDeclare(queueName1, true, false, false, args);
        channel.queueBind(queueName1, EXCHANGE_NAME, "xiaocat");


        //配置死信交换机和死信队列
        Map<String, Object> args2 = new HashMap<>();
        args2.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        args2.put("x-dead-letter-routing-key", "boss");

        //创建第二个队列，这个队列的死信转发到boss死信队列
        String queueName2 = "xiaodog";
        channel.queueDeclare(queueName2, true, false, false, args2);
        channel.queueBind(queueName2, EXCHANGE_NAME, "xiaodog");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        //消息的处理操作
        DeliverCallback fyDeliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            //拒绝消息
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
            System.out.println(" [fy] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };

        DeliverCallback lfyDeliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            //拒绝消息
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
            System.out.println(" [lfy] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };

        channel.basicConsume(queueName1, false, fyDeliverCallback, consumerTag -> {});
        channel.basicConsume(queueName2, false, lfyDeliverCallback, consumerTag -> {});
    }
}
